package com.frontier.gateway8000.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 自定义全局过滤器
 *
 * @author YLS-XuXu
 * @time 2022/2/24
 */
@Slf4j
@Component
@Order(1)
public class SxdGlobalFilter implements GlobalFilter{

    /**
     * 自定义全局拦截器
     *
     * @param exchange
     * @param chain
     * @return reactor.core.publisher.Mono<java.lang.Void>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String path = request.getPath().pathWithinApplication().value();
        //白名单模拟
        if("".equals(path)){
            //如果处于白名单中，直接方行
            return chain.filter(exchange).then(Mono.fromRunnable(()->{
                log.info("请求位于白名单中，直接方行，当前请求路径为：{}",path);
            }));
        }
        //模拟token校验
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            log.info("order1全局拦截器发现token为空，当前请求路径为：{}",path);
        }
        else{
            //模拟token校验
            if(token.equals("1qazxsw23edcvfr45tgbnhy67ujm")){
                log.info("校验通过");
            }else{
                log.info("校验失败，请求路径为,{},请求token为：{}",path,token);
            }
        }
        return chain.filter(exchange);
    }

}
